package com.tanhua.system.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.dubbo.server.api.MessageApi;
import com.tanhua.dubbo.server.pojo.Message;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.system.pojo.UserInfo;
import com.tanhua.system.vo.MessagePageResult;
import com.tanhua.system.vo.MessageVo;
import com.tanhua.system.vo.TotalsVo;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class MessageService {

    @Reference(version = "1.0.0")
    private MessageApi messageApi;

    @Autowired
    private UserInfoService userInfoService;


    /**
     * 消息翻页(查询用户参与过的动态)
     *
     * @param pageSize
     * @param page
     * @param sortProp  排序字段
     * @param sortOrder 升序还是降序
     * @param id        动态的id
     * @param sd        开始时间
     * @param ed        结束时间
     * @param userId    当前查看哪个用户参与过的动态ID
     * @param state     审核状态(all,3,4,5)返回值中的title使用随机数
     * @return
     */
    public MessagePageResult queryMessage(Integer pageSize, Integer page, String sortProp,
                                          String sortOrder, String id, Long sd,
                                          Long ed, Long userId, String state) {
        MessagePageResult messagePageResult = new MessagePageResult();
        messagePageResult.setPage(page);
        messagePageResult.setPagesize(pageSize);

        /*
         * 将需要用到的参数传递到dubbo服务中
         * */
        PageInfo<Message> pageInfo = this.messageApi.queryMessageList(userId, id, pageSize, page, sd, ed, sortProp, sortOrder, state);
        List<Message> records = pageInfo.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            return null;
        }
        //获取 userId列表,用于填充数据
        Set<Long> userIdList = records.stream().map(Message::getUserId).collect(Collectors.toSet());
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIdList);
        List<UserInfo> userInfos = userInfoService.queryUserInfoList(queryWrapper);

        //再通过userId查询用户信息
        List<MessageVo> messageVoList = new ArrayList<>();

        for (Message record : records) {
            for (UserInfo userInfo : userInfos) {
                if (userInfo.getUserId().longValue() == record.getUserId().longValue()) {
                    MessageVo messageVo = this.getMessageVo(record, userInfo);//抽取公共代码
                    messageVoList.add(messageVo);
                }
            }
        }

        List<TotalsVo> totalsVoList = new ArrayList<>();
        totalsVoList.add(TotalsVo.builder().code("all").title("全部").value(29).build());
        totalsVoList.add(TotalsVo.builder().code("3").title("已通过").value(RandomUtils.nextInt(1, 29)).build());
        totalsVoList.add(TotalsVo.builder().code("4").title("待审核").value(RandomUtils.nextInt(1, 29)).build());
        totalsVoList.add(TotalsVo.builder().code("5").title("已驳回").value(RandomUtils.nextInt(1, 29)).build());

        int count = messageVoList.size();
        double pages = ((double) count) / pageSize;

        messagePageResult.setCounts(count);
        messagePageResult.setPages((int) Math.ceil(pages));
        messagePageResult.setItems(messageVoList);
        messagePageResult.setTotals(totalsVoList);

        return messagePageResult;
    }

    /**
     * 消息置顶/取消置顶
     *
     * @param publishId
     * @return
     */
    public Boolean topOrUnTop(String publishId, Integer topState) {
        return this.messageApi.topOrUnTop(publishId, topState);
    }

    /**
     * 消息通过/拒绝
     *
     * @param ids
     * @param state
     * @return
     */
    public Boolean passOrReject(List<String> ids, Integer state) {
        return this.messageApi.passOrReject(ids, state);
    }

    /**
     * 消息撤销
     *
     * @param ids
     * @return
     */
    public Boolean revocationMsg(List<String> ids) {
        return this.messageApi.revocationMsg(ids);
    }

    /**
     * 消息详情
     *
     * @param publishId
     * @return
     */
    public MessageVo queryById(String publishId) {
        Message record = this.messageApi.queryById(publishId);

        UserInfo userInfo = userInfoService.queryUserInfoByUserId(record.getUserId());
        return this.getMessageVo(record, userInfo);
    }

    //填充VO数据
    private MessageVo getMessageVo(Message record, UserInfo userInfo) {
        return MessageVo.builder().id(record.getPublishId().toHexString())
                .nickname(userInfo.getNickName())
                .userId(userInfo.getUserId())
                .userLogo(userInfo.getLogo())
                .createDate(record.getCreateDate())
                .text(record.getText())
                .state(record.getState().toString())
                .topState(record.getTopState())
                .reportCount(record.getReportCount())
                .likeCount(record.getLikeCount())
                .commentCount(record.getCommentCount())
                .forwardingCount(record.getForwardingCount())
                .medias(record.getMedias()).build();
    }
}
